#!/bin/sh
# 构建项目镜像，推送镜像

project_name=demo
nexus_username=admin
nexus_passwd=admin123
nexus_repo=192.168.107.108:8083

image_name=${nexus_repo}/${project_name}

error() {
  echo "\033[31m$(date "+%Y-%m-%d %H:%M:%S") [error] $@ \033[0m"
}

warning() {
  echo "\033[33m$(date "+%Y-%m-%d %H:%M:%S") [warning] $@ \033[0m"
}

info() {
  echo "\033[32m$(date "+%Y-%m-%d %H:%M:%S") [info] $@ \033[0m"
}

check_env() {
  ret=0

  if ! hash docker 2>/dev/null; then
    error "docker not found"
    ret=1
  fi

  if [ $ret -ne 0 ]; then
    exit 1
  fi
}

rename() {
  info "rename jar file..."

  jarName=$(basename "$(ls demo*.jar)")
  if [ -f ${jarName} ]; then
      mv ${jarName} app.jar
  fi
}

# 删除老容器
remove_container() {
  info "remove container..."

  container_id=`docker ps -a|grep ${image_name} |grep -v grep |awk '{print $1}'`
  for id in ${container_id};
  do
  docker stop ${id}
  docker rm ${id}
  done
}

clean() {
  info "remove images..."

  image_id=`docker images |grep ${image_name} |grep -v grep |awk '{print $3}'`
  for id in ${image_id};
  do
  docker rmi ${id}
  done
}

build() {
  info "build..."

  docker build --no-cache -t ${image_name} .
}

push() {
  info "push image to nexus..."

  docker login ${nexus_repo} -u  ${nexus_username} -p  ${nexus_passwd}

  docker push ${image_name}
}

check_env
rename
remove_container
clean
build
push

echo "push success"